/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package org.example.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.common.exception.RRException;
import org.example.common.utils.Constant;
import org.example.common.utils.PageUtils;
import org.example.common.utils.Query;
import org.example.modules.sys.dao.SysUserDao;
import org.example.modules.sys.dto.MyselfDto;
import org.example.modules.sys.entity.SysRoleEntity;
import org.example.modules.sys.entity.SysUserEntity;
import org.example.modules.sys.enums.RegisterEnum;
import org.example.modules.sys.enums.UserStatusEnum;
import org.example.modules.sys.service.SysRoleService;
import org.example.modules.sys.service.SysUserRoleService;
import org.example.modules.sys.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;

	//
	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		String roleName = (String)params.get("roleName");
		Long createUserId = (Long)params.get("createUserId");

		// 组装wrapper
		 QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<SysUserEntity>()
				.like(StringUtils.isNotBlank(username),"username", username)
				.eq(createUserId != null,"create_user_id", createUserId);

		 // 如果指定了roleName，则组装wrapper
		if(StringUtils.isNotBlank(roleName)){
			LambdaQueryWrapper<SysRoleEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(SysRoleEntity::getRoleName,roleName);
			long roleId = sysRoleService.getOne(lambdaQueryWrapper).getRoleId();
			wrapper.exists("SELECT 1 FROM sys_user_role WHERE user_id = sys_user.user_id AND role_id = " + roleId);
		}

		// 组装分页数据的操作，

		IPage<SysUserEntity> page = this.page(
			new Query<SysUserEntity>().getPage(params),
			wrapper
		);

		// 只有什么身份都没有的才是管理员用户
		return new PageUtils(page);
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params, LambdaQueryWrapper<SysUserEntity> lambdaQueryWrapper) {
		IPage<SysUserEntity> page = this.page(
				new Query<SysUserEntity>().getPage(params),
				lambdaQueryWrapper
		);
		return new PageUtils(page);
	}

	/**
	 * 修改用户信息
	 * @param MyselfDto
	 * @return
	 */
	@Override
	public boolean updateMyself(MyselfDto MyselfDto) {
		SysUserEntity sysUser = new SysUserEntity();
		sysUser.setEmail(MyselfDto.getEmail());
		sysUser.setMobile(MyselfDto.getMobile());
		return this.update(sysUser,new QueryWrapper<SysUserEntity>().eq("user_id",MyselfDto.getUseId()));
	}

	// 查询用户所有的权限
	@Override
	public List<String> queryAllPerms(Long userId) {
		return baseMapper.queryAllPerms(userId);
	}

	// 查询用户的所有菜单ID
	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}
	@Override
	public SysUserEntity queryByMobile(String mobile) {
		LambdaQueryWrapper<SysUserEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(SysUserEntity::getMobile,mobile);
		return this.getOne(lambdaQueryWrapper);
	}

	@Override
	@Transactional
	public void saveUser(SysUserEntity user) {
		// 设置头像
		if(StringUtils.isBlank(user.getAvatar())) user.setAvatar("/system/default_avatar.png");
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		// 初始状态未锁定
		if(user.getStatus() == null) user.setStatus(UserStatusEnum.NOT_LOCK);
		this.save(user);
		// 如果user的create-userid为null，则表示为新创用户，需要手动修改
		if(user.getCreateUserId() == null){
			SysUserEntity _user = this.getById(user.getUserId());
			_user.setCreateUserId(_user.getUserId());
			user.setUserId(_user.getUserId());
			user.setCreateUserId(_user.getCreateUserId());
			this.updateById(_user);
		}
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	public void update(SysUserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		this.updateById(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void deleteBatch(Long[] userId) {
		this.removeByIds(Arrays.asList(userId));
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}

	/**
	 * 检查角色是否越权，除了超级管理员外，用户只能创建自己创建过的角色
	 */
	private void checkRole(SysUserEntity user){
		if(user.getRoleIdList() == null || user.getRoleIdList().isEmpty()){
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建，如果是超级管理员，则可以没有限制地创建角色
		if(user.getCreateUserId() == Constant.SUPER_ADMIN){
			return ;
		}
		
		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

		// 判断是否都是可以直接被注册的
		boolean flag = true;
		for (int i = 0; i < roleIdList.size(); i++) {
			SysRoleEntity role = sysRoleService.getById(roleIdList.get(i));
			if(role.getIsRegister() == RegisterEnum.NOT_Register) {
				flag = false;
				break;
			}
		}
		// 如果存在不能被注册的角色则判断是否越权
		if(!flag && !roleIdList.containsAll(user.getRoleIdList())){
			throw new RRException("新增用户所选角色，不是本人创建");
		}
	}
}